namespace PLMonitor;

/// <summary>
/// 通讯适配器基类 具体实现平台相关，类型相关
/// </summary>
public abstract class CommAdapter
{
    /// <summary>
    /// 数据到达委托函数
    /// </summary>
    public delegate void ReceivedHandler(CommAdapter sender, byte[] data, int count);

    /// <summary>
    /// 错误委托函数
    /// </summary>
    public delegate void CommErrorHandler(CommAdapter sender, string errInfo);

    /// <summary>
    /// Occurs when [data received]
    /// </summary>
    public event ReceivedHandler? ReceivedEvent;

    /// <summary>
    /// Occurs when [Com error].
    /// </summary>
    public event CommErrorHandler? ErrorEvent;

    /// <summary>
    /// 打开通讯适配器
    /// </summary>
    public abstract bool Open();

    /// <summary>
    /// 关闭适配器
    /// </summary>
    public abstract void Close();

    /// <summary>
    /// 判断端口是否打开
    /// </summary>
    public abstract bool IsOpened { get; }

    /// <summary>
    /// 通过适配器发送数据
    /// </summary>
    /// <param name="buffer">待发送的无符号类型数据缓冲区.</param>
    /// <param name="offset">待发送的数据偏移量</param>
    /// <param name="count">待发送的数据长度</param>
    public abstract void Write(byte[] buffer, int offset, int count);

    /// <summary>
    /// 通过适配器发送数据
    /// </summary>
    /// <param name="text">待发送的字符串数据</param>
    public abstract void Write(string text);

    /// <summary>
    /// 通过适配器发送数据
    /// </summary>
    public abstract void Write(byte[] buffer);

    /// <summary>
    /// 通知接口数据到达
    /// </summary>
    protected void NotifyDataRcv(byte[] data, int count)
    {
        ReceivedEvent?.Invoke(this, data, count);
    }

    /// <summary>
    /// 通知接口异常
    /// </summary>
    protected void NotifyCommError(string errInfo)
    {
        ErrorEvent?.Invoke(this, errInfo);
    }
    
}//end CommAdapter
